class Users::PasswordsController < Devise::PasswordsController
  # GET /resource/password/new
  # def new
  #   super
  # end

  # POST /resource/password
  # def create
  #   super
  # end

  # GET /resource/password/edit?reset_password_token=abcdef
  # def edit
  #   super
  # end

  # PUT /resource/password
  # def update
  #   super
  # end

  # protected

  # def after_resetting_password_path_for(resource)
  #   super(resource)
  # end

  # The path used after sending reset password instructions
  # def after_sending_reset_password_instructions_path_for(resource_name)
  #   super(resource_name)
  # end
  
  # PUT /resource/password
  def update
    # 检查是否有对应的验证码
    sv = SmsVerification.where(mobile: params[:user][:mobile], 
                        code: params[:code],
                        validated_at: nil,
                        created_at: (Time.now - 20.minutes)..Time.now).order(created_at: :desc).take
    # 检查该手机是否已经注册过
    u = User.find_by_mobile(params[:user][:mobile])
    
    respond_to do |format|
      # 如果证实了该用户的身份
      # 看是否是登录还是注册动作
      if not u
        #帐户不存在
        format.json  { head :bad_request }
        format.html { redirect_to users_forgot_password_path, status: 304 }
      elsif not sv
        #验证码输入不正确
        #注册
        format.json  { head :not_found }
        format.html { redirect_to users_forgot_password_path, status: 304 }
      else
        #更新重置密码
        u.password = params[:user][:password]
        u.save
        sign_in(resource_name, u)
        sv.expire
        format.json  { render json: current_user, status: :created }
        format.html { redirect_to user_profile_path, status: 301 }
      end
    end
  end
end
